import React, { useState, useImperativeHandle, useMemo } from 'react';
import ImagePreview from '@/pages/EntryManage/components/Preview/ImagePreview';
import OfficePreview from '@/pages/EntryManage/components/Preview/OfficePreview';
import PDFPreview from '@/pages/EntryManage/components/Preview/PDFPreview';
import { Modal, Alert } from 'antd';

/**
 * 弹框预览
 * 解决多实例问题, 多个预览可以使用一个组件
 * !!! 暂时简单实现
 */
const PreviewModal = React.forwardRef(({ type, title, width = 800, ...props }, ref) => {
    const [componentType, setComponentType] = useState(type);
    const [visibleModal, setVisibleModal] = useState();
    const [extendConfig, setExtendConfig] = useState();

    useImperativeHandle(ref, () => ({
        open: config => {
            const { type: newType, ...otherConfig } = config || {};
            setComponentType(newType);
            if (otherConfig) {
                setExtendConfig(otherConfig);
            }
            setVisibleModal(true);
        },
        close: () => {
            setVisibleModal(false);
        }
    }));

    const componentConfig = { ...props, ...extendConfig, visible: visibleModal };

    const modalTitle = useMemo(() => {
        const { originName } = componentConfig;
        if (typeof title === 'boolean' && title) {
            return originName;
        }
        if (title) {
            return title;
        }
        return '';
    }, [componentConfig, title]);

    const handlePreViewCancel = () => {
        setVisibleModal(false);
    };

    const renderComponent = () => {
        if (componentType === 'image') {
            return <ImagePreview {...componentConfig} />;
        }
        if (componentType === 'office') {
            return <OfficePreview {...componentConfig} />;
        }
        if (componentType === 'pdf') {
            return <PDFPreview {...componentConfig} />;
        }
        return <Alert message={`抱歉，系统暂不支持预览${modalTitle}`} type="error" />;
    };
    return (
        <Modal title={modalTitle} visible={visibleModal} width={width} onCancel={handlePreViewCancel} footer={null}>
            {renderComponent()}
        </Modal>
    );
});

export default PreviewModal;
